<?php
/**
 * Created By base
 * Author: Virus
 * Date: 2020/4/2
 * Time: 14:49
 */

namespace app\common\handle;

use think\File;

class ImageUploadHandle
{
    // 只允许以下后缀的图片文件
    protected $allowed_ext = ["png", "jpg", "gif", 'jpeg'];

    /**
     * @param $file
     * @param $folder
     * @return bool|string
     */
    public function save(File $file, $folder)
    {
        if ($file) {
            $extension = strtolower($file->getExtension());
            // 如果上传的不是图片终止操作
            if (!in_array($extension, $this->allowed_ext)) {
                return false;
            }
            try {
                $savename = $file->move('/uploads/'.$folder);
            } catch (\Exception $e) {
                return $e->getMessage();
            }
            if ($savename) {
                $path = '/uploads/'.$folder.DIRECTORY_SEPARATOR.$file->getSaveName();

                return $path;
            }
        }

        return false;
    }
}